package com.ccl.iot;import java.lang.reflect.Array;
import java.util.Arrays;

public class IOTMarkedBuffer {
	private boolean iMark[] = null;
	private Object iBuffer = null;
	
	public IOTMarkedBuffer(Object aBuffer, boolean aDefaultMark){
		if (aBuffer != null && aBuffer.getClass().isArray()){
			int tSize = 0;
			
			iBuffer = aBuffer;
			
			if (aBuffer instanceof Object[]){
				tSize = ((Object[]) aBuffer).length;
			}else if (aBuffer instanceof boolean[]){
				tSize = ((boolean[]) aBuffer).length;
			}else if (aBuffer instanceof byte[]){
				tSize = ((byte[]) aBuffer).length;
			}else if (aBuffer instanceof char[]){
				tSize = ((char[]) aBuffer).length;
			}else if (aBuffer instanceof short[]){
				tSize = ((short[]) aBuffer).length;
			}else if (aBuffer instanceof int[]){
				tSize = ((int[]) aBuffer).length;
			}else if (aBuffer instanceof long[]){
				tSize = ((long[]) aBuffer).length;
			}else if (aBuffer instanceof float[]){
				tSize = ((float[]) aBuffer).length;
			}else if (aBuffer instanceof double[]){
				tSize = ((double[]) aBuffer).length;
			}
			
			iMark = new boolean[tSize];
			
			Arrays.fill(iMark, aDefaultMark);
		}
	}
	
	public boolean isAllMarked(){
		if (iMark != null){
			for (int i = 0; i < iMark.length; i++){
				if (iMark[i] == false){
					return false;
				}
			}
			
			return true;
		}
		
		return false;
	}
	
	public boolean put(int aIndex, Object aValue){
		if (iBuffer != null){
			try{
				Array.set(iBuffer, aIndex, aValue);
				
				iMark[aIndex] = true;
				
				return true;
			}catch (Exception e){
				
			}
		}
		
		return false;
	}
	
	public Object getArray(){
		return iBuffer;
	}
	
	public Object get(int aIndex){
		if (iBuffer != null && aIndex < iMark.length){
			return Array.get(iBuffer, aIndex);
		}
		
		return null;
	}
	
	@Override
	public boolean equals(Object aObject){
		if (super.equals(aObject) == false){
			if (aObject != null && aObject instanceof IOTMarkedBuffer){
				IOTMarkedBuffer tBuffer = (IOTMarkedBuffer) aObject;
				
				if (tBuffer.iBuffer != iBuffer){
					if (tBuffer.iBuffer != null){
						if (iBuffer != null){
							int tCount = iMark.length;
							
							if (tCount == tBuffer.iMark.length){
								if (iBuffer.getClass().equals(tBuffer.iBuffer.getClass())){
									for (int i = 0; i < tCount; i++){
										Object tValue1 = get(i);
										Object tValue2 = tBuffer.get(i);
										
										if (tValue1 != null){
											if (tValue1.equals(tValue2) == false){
												return false;
											}
										}else if (tValue2 != null){
											return false;
										}
									}
								}
							}
						}
					}else{
						return iBuffer == null;
					}
				}else{
					return true;
				}
			}
		}
		
		return false;
	}
}
